package com.zw.blog.web;

import com.zw.blog.po.Type;
import com.zw.blog.service.BlogService;
import com.zw.blog.service.TypeService;
import com.zw.blog.vo.BlogQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
public class TypeShowController { // Spring下不能有重名的类

    @Autowired
    private TypeService typeService;

    @Autowired
    private BlogService blogService;

    @GetMapping("/types/{id}")
    public String type(@PageableDefault(size = 5, sort = {"updateTime"}, direction = Sort.Direction.DESC) Pageable pageable,
                       @PathVariable Long id, Model model, HttpSession session) { //传递当前活跃的类型id
        List<Type> types = typeService.listTypeTop(1000);

        // 有问题 得优化
        for (Type type : types) {
            type.initPublishedBlogs(session);
        }

        if (id == -1) { //说明第一次进页面，没有选中类型
            id = types.get(0).getId();
        }
        BlogQuery blogQuery = new BlogQuery();
        blogQuery.setTypeId(id); // ????666666
        blogQuery.setPublished(true);
        if (session.getAttribute("user") == null) {
            blogQuery.setEnableRecommend(true);
        }
        model.addAttribute("types", types);
        model.addAttribute("page", blogService.listBlogPublished(pageable, blogQuery));
        model.addAttribute("activeTypeId", id);
        return "types";
    }
}
